<?php

/**
 * Framework_Module_User_UnwatchRemote
 *
 * @author      Ian Szewczyk <roamzero@gmail.com>
 * @copyright   (c) 2007 Ian Szewczyk. All rights reserved.
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @package Module
 * @filesource
 */

/**
 * Framework_Module_User_UnwatchRemote
 * 
 * 
 *
 * @author Ian Szewczyk <roamzero@gmail.com>
 * @package Module
 */
class Framework_Module_User_UnwatchRemote extends Framework_Module_User
{
		
	/**
	 * $serializerOptions
	 *
	 * @access 		public
	 * @var 		mixed 		$serializerOptions
	 */
	public $serializerOptions = null;

	/**
	 * $signature
	 *
	 * @access 		public
	 * @var 		string 		$signature
	 */
	public $signature;

	/**
	 * $remoteUser
	 *
	 * @access 		public
	 * @var 		object		$remoteUser			Framework_User_Peopletab object
	 */
	public $remoteUser;

	/**
	 * $timeStamp
	 *
	 * @access 		public
	 * @var 		integer 		$timeStamp
	 */
	public $timeStamp;

	/**
	 * $owner
	 *
	 * @access 		private
	 * @var 		object 		$owner
	 */
	private $owner;

	/**
	 * __construct
	 *
	 * Initializes the module: sets the default presenter, the allowed
	 * conrollers, and the allowed events
	 *
	 * @access 		public
	 * @return 		void
	 */
	public function __construct()
	{
		parent::__construct();
		$this->presenter = 'REST';
		 
		if (isset($_POST['signature'])) {
			$this->signature = $_POST['signature'];
		}
		 
		if (isset($_POST['from']) && preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['from'])) {
			$this->remoteUser = explode('@',urldecode($_POST['from']));
		}
		 
		if (isset($_POST['time'])) {
			$this->timeStamp = urldecode($_POST['time']);
		}
	}

	/**
     * __default
     *
     * Generate an XML responce
     *
     * @access 		public
     * @return 		mixed 		boolean true on success, PEAR_Error on failure
     */
	public function __default()
	{
		$this->serializerOptions = array (
		'indent' => '  ',
		'rootName' => 'peopletab',
		'defaultTagName' => 'message');

		$this->owner = Framework_Owner::singleton();
		if ($this->owner->isValid && isset($this->signature) && isset($this->timeStamp) && isset($this->remoteUser)) {
			$result = $this->checkSignature($this->signature, $this->timeStamp, $this->remoteUser);
			if (!PEAR::isError($result)) {
				$result = $this->doUnwatch();
				if (!PEAR::isError($result)) {
					$this->setData('header',
					array('type' => 'UnwatchRemote')
					);
				} else {
					$this->makeError($result->getMessage());
				}

			} else {
				$this->makeError($result->getMessage());
			}

		} else {
			$this->makeError('Invalid Owner');
		}
	}
	 
	/**
     * makeError
     *
     * Generate an XML error
     *
     * @access 		private
     * @param		string		$errorMessage
     * @return 		void
     */
	private function makeError($errorMessage)
	{
		$this->setData('header',
		array('type' => 'error')
		);

		$this->setData('message',
		array('errorMessage' => $errorMessage)
		);

	}
	 
	 
	/**
     * checkSignature
     *
     *
     * @access 		private
     * @return 		mixed 		boolean true on success, PEAR_Error on failure
     */
	private function checkSignature() {

		if (!isset($this->signature) || !isset($this->timeStamp) || !isset($this->remoteUser)) {
			return PEAR::raiseError('Invalid Parameters');
		} else {
			$queryArray = array(
			'sqlKey' => array(
			'select' => 'publicKey',
			'where'  => 'userName = ? AND siteDomain = ?',
			'get'    => 'one'
			  		),
			'params' => array($this->remoteUser[0],$this->remoteUser[1])
			);

			$siteUserTable = Framework_DB::tableFactory('SiteUser');

			$publicKey = $siteUserTable->select($queryArray);
			if (strlen($publicKey) && !PEAR::isError($publicKey)) {
				require_once 'Crypt/RSA.php';
				require_once 'Crypt/RSA/Key.php';
				$key = Crypt_RSA_Key::fromString($publicKey);
				if(!$key->isError()){
					$rsa_obj = new Crypt_RSA;
					if ($rsa_obj->validateSign($this->timeStamp.$this->owner->userName.$this->owner->siteDomain, $this->signature, $key)
					&& ($this->timeStamp + 120) > time()) {
						return true;
					} else {
						if($rsa_obj->isError()) {
							$error = $rsa_obj->getLastError();
							return $error;
						}
						return PEAR::raiseError('Invalid Signature');
					}
				} else {
					return PEAR::raiseError('Invalid Key');
				}
			} else {
				PEAR::raiseError('Cannot Lookup Key');
			}
		}


			
	}
	 

	/**
     * doUnwatch
     *
     * Actually do the unwatch
     *
     * @access 		private
     * @return 		mixed 		boolean true on success, PEAR_Error on failure
     */
	private function doUnwatch()
	{
		$friendStatusTable = Framework_DB::tableFactory('FriendStatus');
	  
		$siteUserTable = Framework_DB::tableFactory('SiteUser');
	  
		$queryArray = array(
		'sqlKey' => array(
		'select' => 'idSiteUser',
		'where'  => 'userName = ? AND siteDomain = ?',
		'get'    => 'one'
	  	 	),
		'params' => array($this->remoteUser[0],$this->remoteUser[1]),

		);
	  
		$idSiteUser = $siteUserTable->select($queryArray);
	  
		$result = $friendStatusTable->update(array('watchedByUser' => 0), array('idOwner' => $this->owner->idOwner, 'idSiteUser' => $idSiteUser));

		if(PEAR::isError($result)) {
			return $result;
		} else {
			return true;
		}
	}
}

?>